package com.molinari.coding;

import java.util.HashMap;
import java.util.Iterator;

import android.content.Context;

import com.molinari.androidstructure.controller.BaseControllore;
import com.molinari.androidstructure.data.db.ConnectionPool;
import com.molinari.coding.dati.ConnectionPoolCoding;
import com.molinari.coding.dati.DatabaseAndroidCoding;
import com.molinari.coding.dati.domain.Utenti;
import com.molinari.coding.dati.domain.dao.WrapCella;
import com.molinari.jdbcandroid.wrap.ConnectionAndroid;

public class ControllerCoding extends BaseControllore {

	private Utenti utenteLogin;
	private int annoRif;
	private static HashMap<String, Boolean> hasConto = new HashMap<String, Boolean>();
	
	static ConnectionAndroid connection;
	
	private static ControllerCoding singleton;
	
	public static ControllerCoding getSingleton() {
		synchronized (ControllerCoding.class) {
			if (singleton == null) {
				singleton = new ControllerCoding();
			}
		}
		return singleton;
	}
	
	public static boolean hasConto(Context context){
		synchronized (hasConto) {
			int idUtente = ControllerCoding.getSingleton().getUtenteLogin().getidUtente();
			String key = Integer.toString(idUtente);
			if(!hasConto.containsKey(key)){
				WrapCella wrapCella = new WrapCella(context);
				@SuppressWarnings("unchecked")
				Iterator<Object> all = (Iterator<Object>) wrapCella.selectByIdUtente(idUtente);
				boolean creato = all.hasNext();
				hasConto.put(key, Boolean.valueOf(creato));
			}
			return hasConto.get(key).booleanValue();
		}
	}
	
	public static void signContoAsCreated(){
		int idUtente = ControllerCoding.getSingleton().getUtenteLogin().getidUtente();
		String key = Integer.toString(idUtente);
		ControllerCoding.hasConto.put(key, Boolean.TRUE);
	}
	
	public static ConnectionAndroid getConnection(Context context){
//		ControllerCoding controller = ControllerCoding.getSingleton();
//		
//		ConnectionPool connectionPool = controller.getConnectionPool(context);
//		return (ConnectionAndroid) connectionPool.getConnection();
		
		connection = new ConnectionAndroid(context, true) {

			@Override
			public Class<?> getDatabaseClass() {
				return DatabaseAndroidCoding.class;
			}
		};
		return connection;
	}
	
	public Utenti getUtenteLogin() {
		return utenteLogin;
	}

	public void setUtenteLogin(Utenti utenteLogin) {
		this.utenteLogin = utenteLogin;
	}

	@Override
	public boolean isLogged() {
		return utenteLogin != null;
	}

	@Override
	protected ConnectionPool createConnectionPool(Context context) {
		return ConnectionPoolCoding.getSingleton(context);
	}

	public int getAnnoRif() {
		return annoRif;
	}

	public void setAnnoRif(int annoRif) {
		this.annoRif = annoRif;
	}

}
